﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TestFireBroadcastingHostPhone.DataBase;

namespace TestFireBroadcastingHostPhone.ViewModel
{
    public class UserConfigMV : ViewModelBase
    {
        public string _RegisterUser_Name = string.Empty;
        /// <summary>
        /// 注册用户名
        /// </summary>
        public string Text_RegisterUser_Name
        {
            get => this._RegisterUser_Name;
            set
            {
                this._RegisterUser_Name = value;
                OnPropertyChanged();
            }
        }

        public string _RegisterUser_Password = string.Empty;
        /// <summary>
        /// 注册用户密码
        /// </summary>
        public string Text_RegisterUser_Password
        {
            get => this._RegisterUser_Password;
            set
            {
                this._RegisterUser_Password = value;
                OnPropertyChanged();
            }
        }

        public string _OldPassword = string.Empty;
        /// <summary>
        /// 用户旧密码
        /// </summary>
        public string Text_OldPassword
        {
            get => this._OldPassword;
            set
            {
                this._OldPassword = value;
                OnPropertyChanged();
            }
        }

        public string _NewPassword = string.Empty;
        /// <summary>
        /// 用户新密码
        /// </summary>
        public string Text_NewPassword
        {
            get => this._NewPassword;
            set
            {
                this._NewPassword = value;
                OnPropertyChanged();
            }
        }
        /// <summary>
        /// 绑定注册用户信息事件
        /// </summary>
        public ICommand Btn_RegisterSQLUerInfoCommand => new RelayCommand(OnBtn_RegisterSQLUerInfo);
        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_RegisterSQLUerInfo(object obj)
        {
            string err_info = string.Empty;
            string password = string.Empty;//读取到的用户密码
            if (!string.IsNullOrEmpty(Text_RegisterUser_Name) && !string.IsNullOrEmpty(Text_RegisterUser_Password))
            {
                password = SQL_ReadUserPassword(Text_RegisterUser_Name, out err_info);
                if (string.IsNullOrEmpty(password))
                {
                    Sql_RegisterUserInfo(Text_RegisterUser_Name, Text_RegisterUser_Password, out err_info);
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        MessageBox.Show("注册失败!" + err_info);
                    }
                    else
                    {
                        MessageBox.Show("注册成功!");
                    }
                }
                else
                {
                    MessageBox.Show("注册失败,当前用户已注册!");
                }
            }
            else
            {
                MessageBox.Show("请输入注册的用户和用户密码!");
            }
        }
        /// <summary>
        /// 绑定修改密码事件
        /// </summary>
        public ICommand Btn_ResetPassword_Command => new RelayCommand(OnResetPassword);
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="obj"></param>
        public void OnResetPassword(object obj)
        {
            string err_info = string.Empty;
            string user_info = string.Empty;
            string oldpassword = string.Empty;
            oldpassword = SQL_ReadUserPassword(UserLoadingMV.userLoadingMV.Text_UserName, out err_info);
            if (!string.IsNullOrEmpty(err_info))
            {
                MessageBox.Show(messageBoxText: $"修改失败: {err_info}", caption: "修改失败", MessageBoxButton.OK, icon: MessageBoxImage.Warning);
                return;
            }
            else
            {
                if (!string.IsNullOrEmpty(oldpassword))
                {
                    if (oldpassword != UserLoadingMV.userLoadingMV.Password_User)
                    {
                        MessageBox.Show(messageBoxText: "管理员原始旧密码错误", caption: "修改失败", MessageBoxButton.OK, icon: MessageBoxImage.Warning);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show(messageBoxText: "当前管理员不存在", caption: "修改失败", MessageBoxButton.OK, icon: MessageBoxImage.Warning);
                    return;
                }
            }
            if (!string.IsNullOrEmpty(Text_NewPassword))
            {
                string newPassword = Text_NewPassword;
                MessageBoxResult result = MessageBox.Show($"确认修改密码为：{newPassword}？", "确认修改", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    SQL_ResetUserPassword(UserLoadingMV.userLoadingMV.Text_UserName, newPassword, out err_info);
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        MessageBox.Show("修改失败,错误信息：" + err_info);
                    }
                    else
                    {
                        MessageBox.Show("密码修改成功!");
                    }
                }
            }
            else
            {
                MessageBox.Show("请输入新密码!");
            }
        }
        /// <summary>
        /// 绑定退出登录事件
        /// </summary>
        public ICommand Btn_QuitLoading_Command => new RelayCommand(OnQuitLoading);
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="obj"></param>
        public void OnQuitLoading(object obj)
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 数据库注册管理员用户数据
        /// </summary>
        /// <param name="Username">用户名</param>
        /// <param name="UserPassword">用户名密码</param>
        /// <param name="error_inf">错误信息</param>
        public void Sql_RegisterUserInfo(string Username, string UserPassword, out string error_inf)
        {
            error_inf = string.Empty;
            string sql_server_name = SQL_DataBase.SQL_Server_Name;
            string sql_data_base_name = SQL_DataBase.SQL_Data_Base_Name;
            string sql_user_name = SQL_DataBase.SQL_User_Name;
            string sql_user_password = SQL_DataBase.SQL_User_Password;
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string table_name = sql_data_base_name + ".dbo.广播主机功放测试用户管理数据表";// 表格名称
            string sql_connect_command_text = "DATA SOURCE=" + sql_server_name + ";INITIAL CATALOG=" + sql_data_base_name + ";USER ID=" + sql_user_name + ";PWD=" + sql_user_password;// SQL连接类的命令字符串
            string sql_command_text = "INSERT INTO " + table_name + "(" + "用户," + "用户密码," + "用户注册时间" + ") VALUES (" + "@用户," + "@用户密码," + "@用户注册时间" + ")";// SQL命令字符串
            try
            {
                using (SqlConnection sql_connection = new SqlConnection(sql_connect_command_text))
                using (SqlCommand sql_command = sql_connection.CreateCommand())
                {
                    sql_connection.Open();
                    sql_command.CommandText = sql_command_text;// 传入数据
                    sql_command.Parameters.Clear();
                    if (Username == string.Empty)
                        sql_command.Parameters.AddWithValue("@用户", DBNull.Value);
                    else
                        sql_command.Parameters.AddWithValue("@用户", Username);
                    if (UserPassword == string.Empty)
                        sql_command.Parameters.AddWithValue("@用户密码", DBNull.Value);
                    else
                        sql_command.Parameters.AddWithValue("@用户密码", UserPassword);
                    sql_command.Parameters.AddWithValue("@用户注册时间", time);
                    int count = sql_command.ExecuteNonQuery();
                    if (count != 1)
                    {
                        error_inf = "SQL插入一行数据失败";
                    }
                }
            }
            catch (Exception ex)
            {
                error_inf = ex.Message;
            }
        }

        /// <summary>
        /// 读取数据库中用户名的密码
        /// </summary>
        /// <param name="User">用户名</param>
        /// <param name="error_inf"></param>
        /// <returns>用户名密码</returns>
        public string SQL_ReadUserPassword(string User, out string error_inf)
        {
            error_inf = string.Empty;
            string password = string.Empty;
            string sql_server_name = SQL_DataBase.SQL_Server_Name;
            string sql_data_base_name = SQL_DataBase.SQL_Data_Base_Name;
            string sql_user_name = SQL_DataBase.SQL_User_Name;
            string sql_user_password = SQL_DataBase.SQL_User_Password;
            string table_name = sql_data_base_name + ".dbo.广播主机功放测试用户管理数据表";
            string sql_connect_command_text = "DATA SOURCE=" + sql_server_name + ";INITIAL CATALOG=" + sql_data_base_name + ";USER ID=" + sql_user_name + ";PWD=" + sql_user_password;
            string sql_command_text = $"SELECT 用户密码 FROM {table_name} WHERE 用户 = @用户";
            try
            {
                using (SqlConnection sql_connection = new SqlConnection(sql_connect_command_text))
                {
                    if (sql_connection.State != ConnectionState.Open)
                    {
                        sql_connection.Open();
                    }
                    using (SqlCommand sql_command = new SqlCommand(sql_command_text, sql_connection))
                    {
                        sql_command.Parameters.AddWithValue("@用户", User);
                        using (SqlDataReader reader = sql_command.ExecuteReader())
                        {
                            if (reader.HasRows && reader.Read())
                            {
                                password = reader["用户密码"].ToString();
                            }
                            else
                            {
                                error_inf = "未找到用户或密码为空";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error_inf = ex.Message;
            }
            return password;
        }

        /// <summary>
        /// 修改数据库用户名密码
        /// </summary>
        /// <param name="Username">用户名</param>
        /// <param name="password">用户名密码</param>
        /// <param name="error_inf">错误信息</param>
        public void SQL_ResetUserPassword(string Username, string password, out string error_inf)
        {
            error_inf = string.Empty;   //错误信息，""为成功
            string sql_server_name = SQL_DataBase.SQL_Server_Name;
            string sql_data_base_name = SQL_DataBase.SQL_Data_Base_Name;
            string sql_user_name = SQL_DataBase.SQL_User_Name;
            string sql_user_password = SQL_DataBase.SQL_User_Password;

            //表格名称
            string table_name = sql_data_base_name + ".dbo.广播主机功放测试用户管理数据表";
            //SQL连接类的命令字符串
            string sql_connect_command_text = "DATA SOURCE=" + sql_server_name + ";INITIAL CATALOG=" + sql_data_base_name + ";USER ID=" + sql_user_name + ";PWD=" + sql_user_password;
            //SQL命令字符串
            string sql_command_text = string.Empty;
            #region SQL命令
            sql_command_text = "UPDATE " + table_name + " SET " +
            "用户 = @用户," +

            "用户密码 = @用户密码 " +

            "WHERE 用户 = '" + Username + "'";
            #endregion
            try
            {
                using (SqlConnection sql_connection = new SqlConnection(sql_connect_command_text))   //创建sql连接类
                using (SqlCommand sql_command = sql_connection.CreateCommand())                       //sql命令类
                {
                    if (sql_connection.State != ConnectionState.Open) sql_connection.Open();   //打开数据库
                    sql_command.CommandText = sql_command_text;    //sql命令赋值
                    sql_command.Parameters.Clear();                //清除全部参数
                    if (Username == string.Empty) sql_command.Parameters.AddWithValue("@用户", DBNull.Value);
                    else sql_command.Parameters.AddWithValue("@用户", Username);

                    if (password == string.Empty) sql_command.Parameters.AddWithValue("@用户密码", DBNull.Value);
                    else sql_command.Parameters.AddWithValue("@用户密码", password);
                    int count = 0;
                    count = sql_command.ExecuteNonQuery();         //执行sql命令
                    if (count != 1)
                    {
                        error_inf = "SQL更新一行临时数据失败";

                        sql_command.Dispose();     //释放数据库命令资源
                        sql_connection.Close();    //关闭数据库连接
                        sql_connection.Dispose();  //释放数据库连接资源
                        return;
                    }
                    sql_command.Dispose();     //释放数据库命令资源
                    sql_connection.Close();    //关闭数据库连接
                    sql_connection.Dispose();  //释放数据库连接资源
                }
            }
            catch (Exception ex)
            {
                error_inf = ex.ToString();
            }
        }
    }
}
